<template>
  <div id="userRegisterPage">
    <h2 class="title">用户注册</h2>
    <div class="desc">企业级智能协同云图库</div>
    <a-form
      :model="formState"
      name="basic"
      label-align="left"
      autocomplete="on"
      @finish="handleSubmit"
    >
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' },{ min: 4, message: '账号长度不能小于 4 位' },]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码不能小于 8 位' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item
        has-feedback
        name="checkPassword"
        :rules="[
          {validator:checkPasswordValidator,trigger:'blur'},
        ]"
      >
        <a-input v-model:value="formState.checkPassword" type="password" placeholder="请再次确认密码" />
      </a-form-item>
      <div class="tips">
        已有账号？
        <RouterLink to="/user/login">去登录</RouterLink>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">注册</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { userRegisterUsingPost } from '@/api/userController.ts'
import { useRouter } from 'vue-router'

const router = useRouter()

interface FormState{
  userAccount: string,
  userPassword: string,
  checkPassword: string,
}
const formState = reactive<FormState>({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
})

//验证两次密码是否输入的一致的validator
const checkPasswordValidator = async(_rule:Rule,value:string)=>{
  // 优化：是否可以在别人配置好的组件上添加“节流”优化，因为trigger:'change'使得每输入一个就进行校验
  // 解决：当鼠标失焦时，再进行校验trigger:'blur'
  // console.log("验证器进来了value：",value)
  if(value === ''){
    return Promise.reject("确认密码不能为空")
  }else if(value!==formState.userPassword){
    return Promise.reject("两次输入不一样")
  }else{
    return Promise.resolve()
  }
}

const handleSubmit = async (values: any) => {
  console.log('点击提交按钮后formState：',values);
  //原生
  // myAxios.post('/register', values).then(res => {
  //   if(res.data.code === 0) {
  //     //跳转到登录页面->(优化：input自带)
  //     router.replace('/user/login')
  //   }else {
  //     message.error(res.data.message)
  //   }
  // }).catch(err => {
  //   console.log(err)
  // })

  //openai
  const res = await userRegisterUsingPost(values)
  if (res.data.code === 0 && res.data.data){
    router.replace('/user/login')
    message.success('注册成功，去登录！')
  }else{
    message.warn(res.data.message)
  }
}
</script>

<style scoped></style>
